<?php


namespace app\api\controller;


use app\api\logic\UserAddressLogic;
use app\common\controller\BaseApiController;
use support\Response;
use support\utils\Time;

class UserAddressController extends BaseApiController
{
    protected function init()
    {
        parent::init();
        $this->logic = new UserAddressLogic();
    }

    public function list()
    {
        $query = $this->logic->search([
            ['user_id', '=', request()->uid],
            ['is_del', '=', 0]
        ]);
        $data = $this->logic->getAll($query);

        return $this->success($data);
    }


    /**
     * 保存数据
     * @return Response
     */
    public function add()
    {
        $data = request()->post();
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $data['user_id'] = request()->uid;
        $this->logic->save($data);
        return $this->success();
    }

    /**
     * 修改数据
     * @return Response
     */
    public function update()
    {
        $id = request()->input("id");
        $data = request()->post();
        if ($this->validate) {
            if (!$this->validate->scene('update')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $data['update_time'] = Time::now();
        $this->logic->update($data, ["id" => $id]);
        return $this->success();
    }

    /**
     * 设置默认值
     * @return Response
     */
    public function setDefault()
    {
        $id = request()->input("id");
        $this->logic->transaction(function () use ($id) {
            $this->logic->where([
                ["id", '=', $id],
                ["user_id", '=', request()->uid],
                ["is_default", '=', 0],
            ])->update(['is_default' => 1]);
            $this->logic->where([
                ["id", '<>', $id],
                ["user_id", '=', request()->uid],
                ["is_default", '=', 1],
            ])->update(['is_default' => 0]);
        });
        return $this->success();
    }

    public function remove()
    {
        $ids = request()->input("id");
        if (!empty($ids)) {
            $this->logic->where(['id', 'in', $ids])->update([
                'is_del' => 1
            ]);
            return $this->success();
        } else {
            return $this->error('参数错误，请检查');
        }
    }

    /**
     * 读取信息
     * @return Response
     */
    public function read()
    {
        if ($this->validate) {
            if (!$this->validate->scene('id')->check(input())) {
                return $this->error($this->validate->getError());
            }
        }
        $model = $this->logic->find(input("id"));
        if ($model) {
            $data = $model->toArray();
            return $this->success($data);
        } else {
            return $this->error('未查找到信息');
        }
    }

}